package com.cff.websocket;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;  
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.cff.domain.User;
import com.cff.util.StringUtil;  
  
public class WebsocketHandler extends TextWebSocketHandler {  
	protected Logger logger = LoggerFactory.getLogger(getClass());
	public static WebSocketUser users = new WebSocketUser();
	public WebsocketHandler(){
		
	}
	
	
    @Override  
    protected void handleTextMessage(WebSocketSession session,  
            TextMessage message) throws Exception {  
    	logger.debug("websocketmsg:{}",message.toString()); 
        super.handleTextMessage(session, message);  
//        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
//        session.sendMessage(returnMessage);  
    }

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		User userInfo = (User) session.getAttributes().get("userInfo");
		String msgType="0000";
		if(userInfo == null){
			long id = users.getWebsocketId();
			logger.info("random UserId:{}",id); 
			users.putUserIdAndWebSocketSession(id+"", session);
			
			session.sendMessage(new TextMessage(msgType+"|"+ id));
		}else{
			logger.info("UserId:{}",userInfo.getLoginId()); 
			//users.putNickNameAndWebSocketSession(userInfo.getNickName(), session);
			users.putUserIdAndWebSocketSession(userInfo.getLoginId(), session);
			session.sendMessage(new TextMessage(msgType+"|"+userInfo.getLoginId()));
		}
		

//		List<TextMessage> message = WebsocketHandler.getOfflineMsg(userInfo.getNickName());
//	    if( message !=null && message.size()!=0){
//	    	for(int i = 0; i < message.size(); i++){
//	    		WebsocketHandler.sendMessageToUser(userInfo.getNickName(), message.get(i));
//	    	}
//	    }
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
//		
//		super.afterConnectionClosed(session, status);
		users.removeWebSocketSession(session);
		
	}
    
	/**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public static void sendMessageToUser(String userName, TextMessage message) {
    	List<WebSocketSession> webUsers = users.getWebSocketSessionWithNickName(userName);
    	System.out.println(webUsers);
    	System.out.println(userName);
    	if (webUsers == null || webUsers.size() == 0){
    		users.putOfflineMsg(userName, message);
    		return;
    	}
    	for(int i =0; i < webUsers.size(); i++){
	    	WebSocketSession user = webUsers.get(i);
	    	System.out.println(user);
	    	
	        try {
	            if (user.isOpen()) {
	            	user.sendMessage(message);
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } 
    	}
    }
    
    /**
     * 根据UserID给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public static void sendMessageToUserWithUserId(String userId, TextMessage message) throws Exception {
    	try{
	    	List<WebSocketSession> webUsers = users.getWebSocketSessionWithUserId(userId);
	    	if (webUsers == null || webUsers.size() == 0){
	    		//users.putOfflineMsg(userName, message);
	    		return;
	    	}
	    	for(int i =0; i < webUsers.size(); i++){
		    	WebSocketSession user = webUsers.get(i);
		    	System.out.println(user);
		    	
		        try {
		            if (user.isOpen()) {
		            	user.sendMessage(message);
		            }
		        } catch (IOException e) {
		            e.printStackTrace();
		        } 
	    	}
    	} catch (Exception e){
    		throw e;
    	}
    }
    
    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public static void sendBinaryMessageToUser(String userId, BinaryMessage message) {
    	List<WebSocketSession> webUsers = users.getWebSocketSessionWithUserId(userId);
    	System.out.println(webUsers);
    	System.out.println(userId);
    	if (webUsers == null || webUsers.size() == 0){
    		//users.putOfflineMsg(userName, message);
    		return;
    	}
    	for(int i =0; i < webUsers.size(); i++){
	    	WebSocketSession user = webUsers.get(i);
	    	System.out.println(user);
	    	
	        try {
	            if (user.isOpen()) {
	            	user.sendMessage(message);
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } 
    	}
    }
    
    public static List<TextMessage> getOfflineMsg(String nickName){
    	return users.getOfflineMsgWithNickName(nickName);
    }
}  
